# -*- coding: utf-8 -*-
"""
	file: word2excel.py
	author: xiangjun.du
	content: words tabel to excel
	create date: 时间
"""
import os
import inspect
import platform
import xlrd
from docx import Document
from optparse import OptionParser
import win32com
from win32com import client
import win32com.client
import shutil
# 获取平台名称，mac编码？
platform_name = platform.system()
# 获取脚本执行路径
script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# 下载源文件路径
download_source_file = os.path.join(script_path, 'data.json')
# 获取平台名称，mac编码？
platform_name = platform.system()
if platform_name.lower() == 'windows':
    platform_encoding = 'gbk'
else:
    platform_encoding = 'utf-8'

word_excel_def = {"产品名称": "存货全名",
                  "收货人": "联系人",
                  "收货人电话": "电话",
                  "收货地址": "客户收货地址",
                  "经销商或用户名称": "单位全名",
                  "是否送货上门、付款方式": "收款方式",
                  "下单时间": "交货日期",
                  "负责人": "负责人",
                  "备注": "备注"}


def get_word_list():
    word_list = []
    for root, dirs, files in os.walk(word_dir, topdown=False):
        for name in files:
            if name.endswith('.doc'):
                doc = os.path.join(root, name)
                docx = os.path.join(words_temp, name).rstrip(".doc") + ".docx"
                doc2docx(doc, docx)
                word_list.append(docx)
            if name.endswith('.docx'):
                docx = os.path.join(root, name)
                docx_temp = os.path.join(words_temp, name)
                shutil.move(docx, docx_temp)
                word_list.append(docx_temp)
    return word_list


def parser_word_list():
    word_keys_list = eval(word_excel).keys()
    words_data_list = []
    for word in word_list:
        word_dict = {}
        # 获取文档对象
        document = Document(word)
        for row in document.tables[0].rows:
            cellk = row.cells[1].text.strip()
            if cellk in word_keys_list:
                word_dict[row.cells[1].text.strip()] = row.cells[2].text.strip()
        word_dict['负责人'] = os.path.basename(word).rstrip('docx')
        words_data_list.append(word_dict)
    return words_data_list


def doc2docx(word_name_doc, word_name_docx):
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(word_name_doc)  # 目标路径下的文件
    # docxname = '%s-docx.docx' % word_name_doc.rstrip('.doc')
    doc.SaveAs(word_name_docx, 12, False, "", True, "", False, False, False, False)  # 转化后路径下的文件
    doc.Close()
    word.Quit()
    # os.remove(word_name)

def get_excel_file_and_write():

    word_excel_dict = eval(word_excel)
    word_excal_values = word_excel_dict.values()
    workbook_r = xlrd.open_workbook(excel_file)
    worksheet_r = workbook_r.sheet_by_index(0)
    nrows = worksheet_r.nrows
    ncols = worksheet_r.ncols

    excel_ncols_index_dict = {}
    for i in range(ncols):
        if worksheet_r.cell_value(0, i).strip() in word_excal_values:
            excel_ncols_index_dict[worksheet_r.cell_value(0, i).strip()] = i+1

    workbook_r.release_resources()
    del workbook_r

    xlApp = win32com.client.Dispatch('Excel.Application')
    xlBook = xlApp.Workbooks.Open(excel_file)
    xlSht = xlBook.Worksheets(worksheet_r.name)

    for word in word_data:
        nrows += 1
        for wk, wv in word.items():
            excel_key = word_excel_dict[wk]
            ncols_index = excel_ncols_index_dict[excel_key]
            xlSht.Cells(nrows, ncols_index).Value = wv

    xlBook.Close(SaveChanges=1)  # 完成 关闭保存文件
    del xlApp


def command_parse():
    """获取命令行参数"""
    usage = r"usage: %prog [options] arg1 arg2, such as 'python word2excle.py -w D:\word2excel\words\ -e D:\word2excel\excel.xls -k {'word-k':'excel-k'}'"
    parser = OptionParser(usage=usage)
    parser.add_option("-w", "--word", action="store", dest="word", help="word文件夹路径", default="D:/word2excel/words/")
    parser.add_option("-e", "--excel", action="store", dest="excel", help="excel文件路径", default="D:/word2excel/excel.xls")
    parser.add_option("-k", "--word_excel", action="store", dest="word_excel", help="word文件下列字段和excel中行字段对应规则字典字符串", default=str(word_excel_def))
    return parser.parse_args()


if __name__ == '__main__':
    print("===开始执行===")
    # 获取命令行参数
    options, args = command_parse()
    word_dir = options.word
    excel_file = options.excel
    word_excel = options.word_excel

    if not word_dir:
        print('请先输入word文件夹路径')
    elif not excel_file:
        print('请先输入excel.xls文件路径')
    elif not word_excel:
        print('请先输入word和excel的对应关系字段')
    else:

        print("--->初始化中...")
        # 生成临时文件夹
        words_temp = os.path.join(word_dir, 'words_temp')
        if os.path.exists(words_temp):
            shutil.rmtree(words_temp)
        os.makedirs(words_temp)
        print("--->读取文档列表中...")
        # 读取word文件列表
        word_list = get_word_list()
        print("--->提取文档内容中...")
        # 解析word文件内容并写入excel
        word_data = parser_word_list()
        print("--->写入excel文档中...")
        # 将解析的word数据保存到excel中
        get_excel_file_and_write()
        print("--->清除缓存文档中...")
        if os.path.exists(words_temp):
            shutil.rmtree(words_temp)

    print("===执行完成===")
